package com.li.network.lab_2;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.util.concurrent.*;

public class PingClient {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        int port = 8086;
        try(DatagramSocket socket = new DatagramSocket()) {
            //设置超时时间1s
            socket.setSoTimeout(1000);
            for (int i = 0; i < 10; i++) {
                long start = System.currentTimeMillis();
                InetAddress serverAddress = InetAddress.getByName("127.0.0.1");
                byte[] ping = ("ping" + i).getBytes();
                DatagramPacket packet = new DatagramPacket(ping, ping.length, serverAddress, port);
                socket.send(packet);
                try {
                    byte[] pong = new byte[1024];
                    DatagramPacket pongPacket = new DatagramPacket(pong, pong.length);
                    socket.receive(pongPacket);
                    long end = System.currentTimeMillis();
                    System.out.println("客户端接收：" + new String(pong, 0, pongPacket.getLength()) + " " + (end - start) + "ms");
                } catch (SocketTimeoutException e) {
                    System.out.println("超时"+i);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
